// JavaScript Document
document.write("<script language='javascript' src='./js/jquery.cookie.js' ></script>");
document.write("<script language='javascript' src='./js/layer/layer.js' ></script>");
document.write("<script language='javascript' src='./js/API.js' ></script>");
document.write("<script language='javascript' src='./js/left_nav.js' ></script>");
document.write("<script language='javascript' src='./js/page.js' ></script>");

var API = null;
var IMG_PREFIX= 'http://7xlaxq.com1.z0.glb.clouddn.com/';


$(document).ready(function () {
    $("#header").html('<h1><img src="./images/admin_logo.png"/></h1>'+
        '<ul class="rt_nav">' +
        '<li><a href="javascript:void(0);" onclick="do_logout();" class="quit_icon">安全退出</a></li>' +
        '</ul>'
    );


    $('#left_nav').append(nav_left);
    $('.lt_aside_nav a').removeClass('active');
    $('.lt_aside_nav a').eq(parseInt(getParam('select'))).addClass('active');

    API = new APIBase();

    (function($){
        $(window).load(function(){

            $("a[rel='load-content']").click(function(e){
                e.preventDefault();
                var url=$(this).attr("href");
                $.get(url,function(data){
                    $(".content .mCSB_container").append(data); //load new content inside .mCSB_container
                    //scroll-to appended content
                    $(".content").mCustomScrollbar("scrollTo","h2:last");
                });
            });

            $(".content").delegate("a[href='top']","click",function(e){
                e.preventDefault();
                $(".content").mCustomScrollbar("scrollTo",$(this).attr("href"));
            });

        });
    })(jQuery);
});

function nav_jump(e,id){
    if(id == 1 || id == 2){
        window.location.href = e.attr('data-href') + '?pharmacy=' + getParam('pharmacy') + '&select='+id;
    }else{
        window.location.href = e.attr('data-href') + '?pharmacy=' + getParam('pharmacy') + '&select='+id + '&p=1';
    }
}


function messageBox(content,type,callback) {
    if(!content){
        layer.alert("消息未知");
    }
    switch (type){
        case 'alert':
            layer.alert(content, {icon: 2});
            break;
        case 'msg':
            layer.msg(content, {icon: 1});
            break;
        case 'load':
            layer.load(content, {icon: 2});
            break;
        case 'logout':
            layer.confirm(content, {
                btn: ['确认', '取消'] //可以无限个按钮
            }, function(index, layero){
                //退出登录需要清除掉所有localStorage和sessionStorage
                $.cookie('user_token', '', {expires: -1, path: '/'});
                localStorage.clear();
                sessionStorage.clear();
                window.location.href = './login.html';
            }, function(index){
                layer.close();
            });
            break;
        case 'confirm':
            layer.confirm(content, {
                btn: ['确认', '取消'] //可以无限个按钮
            }, function(index, layero){
                //退出登录需要清除掉所有localStorage和sessionStorage
                callback();
            }, function(index){
                layer.close();
            });
            break;
        default :
            layer.open({
                type:2,
                title:"请选择操作",
                area:['500px','300px'],
                shadeClose:true,
                content:content
            });
            break;
    }
}

function loadJS(file_name) {
    document.write("<script language='javascript' src='./js/custom/"+ file_name + ".js' ></script>");
}


function do_logout() {
    //退出登陆,需要跳转回登陆页面,然后去掉cookie
    messageBox("退出登录?",'logout')

}

function getNoneReplay(){
    $('#has_no_msg').empty().append("<span style='color:red;'>没有获取到数据,点击<a href='javascript:void(0);' onclick='window.location.reload();'>这里</a>重试</span>")
}

function getNetErrorReplay(){
    $('#has_no_msg').empty().append("<span style='color:red;'>网络获取错误,点击<a href='javascript:void(0);' onclick='window.location.reload();'>这里</a>重试</span>")
}

function getUserToken() {
    console.log(window.location.pathname);
    if(window.location.pathname != '/login.html') {
        cookie_get = $.cookie('user_token');
        if (cookie_get != undefined) {
            return cookie_get;
        } else {
            local_get = localStorage.getItem('user_token');
            if (local_get != undefined) {
                local_get_timeout = localStorage.getItem('user_token_' + local_get);
                nowDate = new Date().getTime();
                if (nowDate > local_get_timeout) {
                    //清理掉过期的数据
                    localStorage.removeItem('user_token');
                    localStorage.removeItem('user_token_' + local_get);
                    messageBox("登陆信息已过期,请重新登陆", 'alert');
                    setTimeout(function () {
                        window.location.href = './login.html';
                    }, 2000);
                } else {
                    return local_get;
                }
            } else {
                //这里查看sessionStorage
                slocal_get = sessionStorage.getItem('user_token');
                if (slocal_get != undefined) {
                    return slocal_get;
                } else {
                    messageBox("请先登陆本系统", 'alert');
                    setTimeout(function () {
                        window.location.href = './login.html';
                    }, 2000);
                }

            }
        }
    }else{
        return '';
    }
    return '';
}

var doShow = function(table_name,msg,getStatus){
    console.log(msg);
    if(getStatus){
        table_obj = $('#'+table_name);
        //获取所有的th的id,他们表示的就是名
        ths = table_obj.find('th');
        attrs = [];
        for(var i= 0;i<ths.length;i++){
            attrs.push(ths[i].getAttribute('id'));
        }
        //对相应的数据进行展示
        if(msg.length == 0){
            getNoneReplay();
            return false;
        }else{
            $('#has_no_msg').parent().empty();
            for(var j = 0; j < msg.length; j++){
                tr = document.createElement('tr');
                for(var m=0;m<attrs.length;m++){
                    td = document.createElement('td');
                    if(m == attrs.length-1){
                        td.innerHTML = '<a href="/index.html?pharmacy='+ msg[j]['objectId'] +'">查看详情</a>';
                    }else{
                        td.innerText = msg[j][attrs[m]];
                    }

                    tr.appendChild(td);
                }
                table_obj.append(tr);
            }
        }
    }else{
        messageBox(msg,'alert');
        getNoneReplay();
    }
};


var doShowDrug = function(table_name,msg,getStatus){
    console.log(msg);
    if(getStatus){
        table_obj = $('#drug_table');
        //对相应的数据进行展示
        if(msg.length == 0){
            getNoneReplay();
            return false;
        }else{
            $('#has_no_msg').parent().empty();
            for(var i=0 ;i<msg.drug_list.length;i++){
                temp = msg.drug_list[i];
                tr = '<tr>';
                tr += '<td><img src="' + ((temp.drug_base_info.images.thumb[0].indexOf('http://'))?IMG_PREFIX+temp.drug_base_info.images.thumb[0]:temp.drug_base_info.images.thumb[0]) + '"onclick="showBigPic($(this))" width="40px" height="40px" /></td>';
                tr += '<td>' + temp.drug_base_info.product_name + '</td>';
                tr += '<td>' + temp.drug_base_info.instructions.生产企业 + '</td>';
                tr += '<td>' + temp.drug_base_info.drug_form + '</td>';
                tr += '<td>' + getStatusShow(temp.is_recommend) + '</td>';
                tr += '<td>' + getStatusShow(temp.is_sale) + '</td>';
                tr += '<td>' + getStatusShow(temp.unsold) + '</td>';
                tr += '<td>' + temp.price + '</td>';
                tr += '<td>' + temp.sale_price + '</td>';
                tr += '</tr>';
                table_obj.append(tr);
            }
        }
        //分页
        $('#page').createPage({
            pageCount:Math.ceil(msg.drug_count/20),
            current:parseInt(getParam('p')),
            backFn: function (p) {
                window.location.href = window.location.href.replace('p='+getParam('p'),'p='+p);
            }
        })
    }else{
        getNoneReplay();
    }
};

var doShowDrugShort = function(table_name,msg,getStatus){
    console.log(msg);
    if(getStatus){
        table_obj = $('#drug_table');
        //对相应的数据进行展示
        if(msg.length == 0){
            getNoneReplay();
            return false;
        }else{
            $('#has_no_msg').parent().empty();
            for(var i=0 ;i<msg.drug_list.length;i++){
                temp = msg.drug_list[i];
                tr = '<tr>';
                tr += '<td><img src="' + ((temp.drug_base_info.images.thumb[0].indexOf('http://'))?IMG_PREFIX+temp.drug_base_info.images.thumb[0]:temp.drug_base_info.images.thumb[0]) + '"onclick="showBigPic($(this))" width="40px" height="40px" /></td>';
                tr += '<td>' + temp.drug_base_info.product_name + '</td>';
                tr += '<td>' + temp.drug_base_info.instructions.生产企业 + '</td>';
                tr += '<td>' + temp.drug_base_info.drug_form + '</td>';
                tr += '<td>' + temp.price + '</td>';
                tr += '<td>' + temp.sale_price + '</td>';
                tr += '</tr>';
                table_obj.append(tr);
            }
        }
        //分页
        $('#page').createPage({
            pageCount:Math.ceil(msg.drug_count/20),
            current:parseInt(getParam('p')),
            backFn: function (p) {
                window.location.href = window.location.href.replace('p='+getParam('p'),'p='+p);
            }
        })
    }else{
        getNoneReplay();
    }
};


function getStatusShow(status){
    return (status) ? '<div class="gou"></div>' : '<div class="no-gou"></div>'
}


var getParam = function(name){
    var search = document.location.search;
    var pattern = new RegExp("[?&]"+name+"\=([^&]+)", "g");
    var matcher = pattern.exec(search);
    var items = null;
    if(null != matcher){
        try{
            items = decodeURIComponent(decodeURIComponent(matcher[1]));
        }catch(e){
            try{
                items = decodeURIComponent(matcher[1]);
            }catch(e){
                items = matcher[1];
            }
        }
    }
    if(name == 'p' && items == null){
        items = 1;
    }
    return items;
};

function showBigPic(e){
    src = e.attr('data-src');
    if(typeof(src) == 'undefined'){
        src = e.attr('src');
    }
    console.log(e);
    layer.open({
        type: 1,
        title: false,
        area: ['800px', '600px'],
        shadeClose: true, //点击遮罩关闭
        content: '<div class="big-pic"><img src="' +src+'" width="800px" height="600px" ></div>'
    })
}














